<template>
    <div class="main">
        <div class="air-column">
            <h2>乘机人</h2>

            <el-form class="member-info" :model="{ users }" ref="usersForm">
                <!-- 表单只有一个 -->
                <!-- 这里的 div 可以跟随数组的长度进行遍历 -->
                <div
                    class="member-info-item"
                    v-for="(user, index) in users"
                    :key="index"
                >
                    <el-form-item
                        label="姓名"
                        :rules="[
                            {
                                required: true,
                                message: '请填写乘机人姓名',
                                trigger: 'blur',
                            },
                        ]"
                        :prop="`users[${index}].username`"
                    >
                        <el-input
                            v-model="user.username"
                            placeholder="请输入乘机人姓名"
                            class="input-with-select"
                        >
                        </el-input>
                    </el-form-item>

                    <el-form-item
                        label="身份证"
                        :rules="[
                            {
                                required: true,
                                message: '请填写身份证号',
                                trigger: 'blur',
                            },
                        ]"
                        :prop="`users[${index}].id`"
                    >
                        <el-input
                            v-model="user.id"
                            placeholder="填写身份证号码"
                            class="input-with-select"
                        >
                        </el-input>
                    </el-form-item>

                    <span class="delete-user" @click="handleDeleteUser(index)"
                        >-</span
                    >
                </div>
            </el-form>

            <el-button class="add-member" type="primary" @click="handleAddUsers"
                >添加乘机人</el-button
            >
        </div>

        <div class="air-column">
            <h2>保险</h2>
            <el-checkbox-group v-model="insurances">
                <div
                    class="insurance-item"
                    v-for="item in data.insurances"
                    :key="item.id"
                >
                    <el-checkbox :label="item.id" border>
                        {{ item.type }}: ￥{{ item.price }} / 份 X
                        {{ users.length }} 最高赔付 {{ item.compensation }}
                    </el-checkbox>
                </div>
            </el-checkbox-group>
            <h2>发票</h2>
            <el-checkbox v-model="invoice">申请发票</el-checkbox>
        </div>

        <div class="air-column">
            <h2>联系人</h2>
            <div class="contact">
                <el-form
                    ref="contactForm"
                    label-width="80px"
                    :model="{
                        contactName,
                        contactPhone,
                        captcha,
                    }"
                    :rules="contactRules"
                >
                    <el-form-item label="姓名" prop="contactName">
                        <el-input
                            v-model="contactName"
                            @focus="clearErrMsg('contactName')"
                        ></el-input>
                    </el-form-item>

                    <el-form-item label="手机" prop="contactPhone">
                        <el-input
                            placeholder="请输入内容"
                            v-model="contactPhone"
                            @focus="clearErrMsg('contactPhone')"
                        >
                            <template slot="append">
                                <el-button @click="handleSendCaptcha"
                                    >发送验证码</el-button
                                >
                            </template>
                        </el-input>
                    </el-form-item>

                    <el-form-item label="验证码" prop="captcha">
                        <el-input
                            v-model="captcha"
                            @focus="clearErrMsg('captcha')"
                        ></el-input>
                    </el-form-item>
                </el-form>
                <el-button
                    v-if="$store.state.userstore.userInfo.token"
                    type="warning"
                    class="submit"
                    @click="handleSubmit"
                    >提交订单</el-button
                >
            </div>

            <el-row
                v-if="!$store.state.userstore.userInfo.token"
                type="flex"
                justify="center"
                align="middle"
                class="main"
            >
                <div class="form-wrapper">
                    <!-- 表单头部tab -->
                    <el-row type="flex" justify="center" class="tabs">
                        <span
                            :class="{ active: currentTab === index }"
                            v-for="(item, index) in [`登录`, `注册`]"
                            :key="index"
                            @click="handleChangeTab(index)"
                        >
                            {{ item }}
                        </span>
                    </el-row>

                    <!-- 登录功能组件 -->
                    <LoginForm v-if="currentTab == 0" />

                    <!-- 注册功能组件 -->
                    <RegisterForm
                        v-if="currentTab == 1"
                        @toLogin="currentTab = 0"
                    />
                </div>
            </el-row>

            <div style="display: none">
                {{ totalPrice }}
            </div>
        </div>
    </div>
</template>

<script>
    import LoginForm from "@/components/user/LoginForm";
    import RegisterForm from "@/components/user/RegisterForm";
    export default {
        props: ["data"],
        data() {
            return {
                currentTab: 0,
                contactRules: {
                    contactName: [
                        {
                            required: true,
                            message: "请输入联系人",
                            trigger: "blur",
                        },
                    ],
                    contactPhone: [
                        {
                            required: true,
                            message: "请输入手机号",
                            trigger: "blur",
                        },
                    ],
                    captcha: [
                        {
                            required: true,
                            message: "请输入验证码",
                            trigger: "blur",
                        },
                    ],
                },
                // 乘机人应该是一个数组
                // 里面的每个对象都是一个乘机人
                // 添加删除的实话, 只需要 push / splice
                users: [
                    {
                        username: "",
                        id: "412343454345445666",
                    },
                ],
                insurances: [],
                contactName: "",
                contactPhone: "13435666666",
                captcha: "000000",
                invoice: false,
            };
        },
        components: {
            LoginForm,
            RegisterForm,
        },
        computed: {
            totalPrice() {
                let res = 0;
                // 1. 机票价格
                res += this.data.base_price * this.users.length;
                // 2. 保险价格

                // 当前被选中的保险是 this.insurances, 需要遍历能够拿到选中的 id
                this.insurances.forEach((idSelected) => {
                    // 这里拿到id 需要到原来总的保险数据中查找出对应的价格
                    // 当前所有保险数据在 this.data.insurances, 可以拿到每个保险的对象
                    this.data.insurances.forEach((element) => {
                        if (element.id == idSelected) {
                            res += element.price * this.users.length;
                        }
                    });
                });

                console.log(res);

                this.$emit("setTotalPrice", res);

                return res;
            },
        },
        // watch 默认不变化不触发
        // 解决方案一, 手动在创建时触发一次
        // created() {
        //     this.calcTotalPrice();
        // },
        // watch: {
        //     // users() {
        //     //     // 计算总价格
        //     //     console.log('乘机人变化了');
        //     //     this.calcTotalPrice()
        //     // },
        //     // 可以讲一个 watch 改成进来马上出发一次
        //     users: {
        //         handler() {
        //             console.log('乘机人变化了');
        //             this.calcTotalPrice()
        //         },
        //         immediate: true
        //     },
        //     insurances() {
        //         // 计算总价格
        //         console.log('保险变化了');
        //         this.calcTotalPrice()
        //     }
        // },
        methods: {
            handleChangeTab(index) {
                this.currentTab = index;
            },
            clearErrMsg(propName) {
                this.$refs.contactForm.clearValidate(propName);
            },
            calcTotalPrice() {
                let res = 0;
                // 1. 机票价格
                res += this.data.base_price * this.users.length;
                // 2. 保险价格

                // 当前被选中的保险是 this.insurances, 需要遍历能够拿到选中的 id
                this.insurances.forEach((idSelected) => {
                    // 这里拿到id 需要到原来总的保险数据中查找出对应的价格
                    // 当前所有保险数据在 this.data.insurances, 可以拿到每个保险的对象
                    this.data.insurances.forEach((element) => {
                        if (element.id == idSelected) {
                            res += element.price * this.users.length;
                        }
                    });
                });

                console.log(res);

                this.$emit("setTotalPrice", res);
            },
            handleSubmit() {
                // 进行总的校验
                // 一共两个表单

                // this.$refs.usersForm.validate().then((isValidUsers) => {
                //     // 这里是乘机人校验成功
                //     if (isValidUsers) {
                //         this.$refs.contactForm.validate().then((isValidContact) => {
                //             // 这里是联系人校验成功
                //             if (isValidContact) {
                //                 // 这里才是两个都校验完真正发送的地方
                //             }
                //         });
                //     }
                // });
                Promise.all([
                    this.$refs.usersForm.validate(),
                    this.$refs.contactForm.validate(),
                ]).then((res) => {
                    // 因为 Promise.all 传入了两个元素组成的数组
                    // 所以 res 也是一个数组对应,上面promise 的结果
                    if (res[0] && res[1]) {
                        console.log("提交请求");
                        // console.log(this.users);
                        // console.log(this.insurances);
                        // console.log(this.contactName);
                        // console.log(this.contactPhone);
                        // console.log(this.captcha);
                        const data = {
                            users: this.users,
                            insurances: this.insurances,
                            contactName: this.contactName,
                            contactPhone: this.contactPhone,
                            invoice: this.invoice,
                            seat_xid: this.$route.query.seat_xid,
                            air: this.$route.query.id,
                            // 文档少了一个验证码需要自己加上
                            captcha: this.captcha,
                        };

                        this.$axios({
                            method: "post",
                            url: "/airorders",
                            data,
                            headers: {
                                Authorization:
                                    "Bearer " +
                                    this.$store.state.userstore.userInfo.token,
                            },
                        }).then((res) => {
                            console.log(res.data);
                            const { data, message } = res.data;

                            if (message == "订单提交成功") {
                                this.$message.success("订单提交成功");
                                this.$router.push("/air/pay?id=" + data.id);
                            }
                        });
                    }
                });
            },
            handleAddUsers() {
                this.users.push({
                    username: "",
                    id: "",
                });
            },
            handleDeleteUser(index) {
                this.users.splice(index, 1);
            },
            handleSendCaptcha() {
                this.$axios({
                    url: "/captchas",
                    method: "post",
                    data: {
                        tel: this.contactPhone,
                    },
                }).then((res) => {
                    console.log(res.data);
                    if (res.data.code) {
                        this.$message.success("获取到验证码：" + res.data.code);
                    }
                });
            },
        },
    };
</script>

<style scoped lang="less">
    .air-column {
        border-bottom: 1px #ddd dashed;
        padding-bottom: 20px;
        margin-bottom: 20px;
    }

    .air-column h2 {
        margin-bottom: 20px;
        font-size: 22px;
        font-weight: normal;
    }

    /deep/ .el-select .el-input {
        width: 130px;
    }

    .input-with-select {
        width: 590px;
    }

    .input-with-select /deep/ .el-input-group__prepend {
        background-color: #fff;
    }
    .member-info /deep/ .el-form-item {
        margin-bottom: 8px;
    }

    // 这里是每个乘机人的外容器
    .member-info-item {
        border-bottom: 1px #eee dashed;
        padding-bottom: 20px;
        position: relative;

        &:first-child {
            .delete-user {
                display: none;
            }
        }
    }

    .add-member {
        margin-top: 20px;
    }

    .delete-user {
        display: block;
        background: #ddd;
        width: 16px;
        height: 16px;
        font-size: 14px;
        text-align: center;
        line-height: 16px;
        color: #fff;
        cursor: pointer;
        border-radius: 50px;
        position: absolute;
        right: -30px;
        top: 50%;
    }

    .insurance {
        > div {
            margin-top: 10px;
        }
    }

    .insurance-item {
        margin-bottom: 20px;
    }

    .contact {
        /deep/ .el-input {
            width: 50%;
        }
    }

    .submit {
        margin: 50px auto;
        display: block;
        width: 250px;
        height: 50px;
    }

    .main {
        height: 100%;
        margin: 0 auto;
        position: relative;

        .form-wrapper {
            width: 400px;
            margin: 0 auto;
            background: #fff;
            box-shadow: 2px 2px 0 rgba(0, 0, 0, 0.1);
            overflow: hidden;

            .tabs {
                span {
                    display: block;
                    width: 50%;
                    height: 50px;
                    box-sizing: border-box;
                    border-top: 2px #eee solid;
                    background: #eee;
                    line-height: 48px;
                    text-align: center;
                    cursor: pointer;
                    color: #666;

                    &.active {
                        color: orange;
                        border-top-color: orange;
                        background: #fff;
                        font-weight: bold;
                    }
                }
            }
        }
    }
</style>